import { container } from '../di/container';
import { LoggerToken } from '../domain/interfaces/ILogger';
import type { ILogger } from '../domain/interfaces/ILogger';
import { WebSocketHandler } from './websocketHandler';

// 初始化依赖注入
import '../di/container';

let _logger: ILogger | undefined;
function getLogger(): ILogger {
  if (!_logger) _logger = container.resolve<ILogger>(LoggerToken);
  return _logger;
}

export class WebSocketServer {
  private server: any;

  start(port: number = 3000): void {
    // @ts-ignore Bun global is present when running under Bun
    this.server = Bun.serve({
      port,
      fetch: (req, server) => {
        if (!this.authenticate(req)) {
          return new Response('Unauthorized', { status: 401 });
        }

        // server.upgrade 在 Bun 的类型定义中可能与自定义上下文不匹配，使用 any 安全调用
        if ((server as any).upgrade(req, { data: {} })) {
          return;
        }
        return new Response('Upgrade failed', { status: 500 });
      },
      websocket: {
        // 将 Bun 的 websocket 实例断言为 any 再传入自定义处理器以避免类型不匹配
        open: (ws) => WebSocketHandler.onOpen(ws as any),
        message: (ws, message) => WebSocketHandler.onMessage(ws as any, message.toString()),
        close: (ws) => WebSocketHandler.onClose(ws as any),
      },
    });

  getLogger().info(`WebSocket server running on ${this.server.hostname}:${port}`);
  }

  private authenticate(req: Request): boolean {
    return true; // 简化示例
  }

  stop(): void {
  this.server?.stop();
  getLogger().info('WebSocket server stopped');
  }
}
